package ofpof.web.validator;

import ofpof.domain.CaptchaToken;
import ofpof.service.CaptchaService;
import ofpof.web.form.PasswordReminderForm;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Component
public class PasswordReminderFormValidator implements Validator {
	
	@Autowired
	private CaptchaService captchaService;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return PasswordReminderForm.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object form, Errors errors) {
		
		PasswordReminderForm reminderForm = (PasswordReminderForm) form;
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"email", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"captcha", "field.required");
		
		if (!errors.hasFieldErrors("email")) {
			boolean isValidEmail = UserFormValidator.emailPattern.matcher(reminderForm.getEmail()).matches();
			if (!isValidEmail) {
				errors.rejectValue("email", "user.email.invalid");
				return;
			}
		}
	
		if (!errors.hasFieldErrors("captcha")) {
			ObjectId captchaId = new ObjectId(reminderForm.getCaptchaId());
			CaptchaToken captchaToken = captchaService.findValidTokenById(captchaId);
			if (!reminderForm.getCaptcha().equals(captchaToken.getCaptchaText())) {
				errors.rejectValue("captcha", "captcha.no.match");
			}
		}
	}

}
